# -*- coding: utf-8 -*-
'''
@File: view.py
@Time: 2023/5/5 23:34
@Author: sunda
'''
'''
viwe 视图
'''
"""登录的视图函数"""
from flask import session, request, render_template, redirect, url_for, flash,  send_from_directory
from flask_login import login_required, login_user
from . import login
from app.models import User, Holiday, DictType, DictItem
from .utils import get_year, get_area, get_holiday, get_dict_type, get_dict_item, dict_add, \
    get_dict_type_by_typeid, dict_type_update, dict_type_delete
from app import login_manager
from app.form import LoginForm,CalendarForm,DictTypeFrom,DictItemFrom
import calendar
import os
import uuid
from datetime import datetime
from werkzeug.utils import secure_filename
from config import BaseConfig
from ..execel_data import get_excel

@login_manager.user_loader
def load_user(user_id):  # 创建用户加载回调函数，接受用户 ID 作为参数
    user = User.query.get(int(user_id))  # 用 ID 作为 User 模型的主键查询对应的用户
    return user  # 返回用户对象

def calc_calender(date):
    '''
    根据日期获取日历列表
    date 当前日期 2023 05 07 12:12:18
    '''
    year = date.year
    yearInfo = dict()
    for month in range(1, 13):
        days = calendar.monthcalendar(year, month)
        if len(days) != 6:
            days.append([0 for _ in range(7)])
        month_addr = calendar.month_abbr[month]
        yearInfo[month_addr] = days
    return yearInfo

def set_yead(yead):
    '''
    #获取当前年份的前后三年
    yead 2023
    '''
    yeads=[(yead,yead)]
    for i in range(1,4):
        yeads.insert(i-1,(yead-i,yead-i))
        yeads.insert(i-1, (yead + i, yead + i))
    yeads_list=sorted(yeads)
    yeads_list.insert(0,('None','请选择年份'))
    return yeads_list

#登录成功后展示首页
@login.route('/index', methods=['GET', 'POST'])
@login_required #需要进行登录验证后才能访问的路由
def index():
    form = CalendarForm()
    months = {'1': 'Jan', '2': 'Feb', '3': 'Mar', '4': 'Apr', '5': 'May', '6': 'Jun', '7': 'Jul', '8': 'Aug',
              '9': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec'}
    calendar.setfirstweekday(firstweekday=6)
    date = datetime.today()
    this_month = calendar.month_abbr[date.month]
    holiday=[]
    year = date.year
    area = '中国内地'
    if request.method == "GET" or request.method == "POST":
        if form.year.data==None or form.area.data==None:
            print("默认年份")
            form.year.choices = set_yead(int(year))  # 替换下拉框选项数据
            # print(set_yead(int(year)))
            holiday = get_holiday(year,area) #获取节假日数据
        else:
            print(form.year.data)
            if form.year.data != 'None':
                print("指定年份")
                if len(get_year(int(form.year.data)))==0 or len(get_area(form.area.data))==0:
                    #如果年份和地区无数据 弹出flash消息
                    flash("无符合查询条件数据，请重试")
                    return redirect(url_for('login.index'))
                else:
                    form.year.choices = set_yead(int(form.year.data))
                    holiday = get_holiday(int(form.year.data), form.area.data)  # 获取节假日数据
            else:
                form.year.choices = set_yead(int(year))  # 替换下拉框选项数据
                holiday = get_holiday(date.year, area)  # 获取节假日数据
        '''节假日日期替换为休'''
        content = calc_calender(date)
        for i in range(len(holiday)):
            month=holiday[i][1].split('-')
            month[0]=months.get(month[0])
            for key, values in content.items():
                if month[0] == key:
                    for i in range(len(values)):
                        for j in range(len(values[i])):
                            if values[i][j] == int(month[1]):
                                values[i][j] = '休'
        return render_template('index.html',this_month=this_month, date=date, content=content,form=form)

#模板文件上传
@login.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    # 如果是get请求响应上传视图，post请求响应上传文件
    if request.method == 'GET':
        return render_template('upload.html')
    else:
        f = request.files['file']
        fname = secure_filename(f.filename)
        ext = fname.rsplit('.')[-1]
        # 生成一个uuid作为文件名
        fileName = str(uuid.uuid4()) + "." + ext
        # os.path.join拼接地址，上传地址，f.filename获取文件名
        f.save(os.path.join(BaseConfig.UPLOAD_FOLDER, fileName))
        '''上传成功后将表格数据添加至数据库'''
        if os.path.splitext(fname)[1]=='xlsx' or os.path.splitext(fname)[1]=='xlsx'=='xls':
            data=get_excel(os.path.join(BaseConfig.UPLOAD_FOLDER, fileName))
            commit_data=[]
            for i in range(len(data)):
                commit_data.append(Holiday(year=data[0],date=data[1],area=data[2],note=data[3]))
            from app import db
            db.session.add_all(commit_data)
            db.session.commit()
        return redirect(url_for('login.index'))  # 重定向到主页

# 文件下载
@login.route('/download/<filename>', methods=['GET', 'POST'])
def download(filename):
    '''
    send_from_directory：用于下载文件
    flask.send_from_directory(所有文件的存储目录，相对于要下载的目录的文件名，as_attachment：设置为True是否要发送带有标题的文件)
    '''
    # 通过文件名下载文件
    path = os.path.isfile(os.path.join(BaseConfig.UPLOAD_FOLDER, filename))
    if path:
        return send_from_directory(BaseConfig.UPLOAD_FOLDER, filename, as_attachment=True)

#数据字典主页
@login.route('/system_dict', methods=['GET', 'POST'])
@login_required
def system_dict():
    form=DictTypeFrom()
    type_id=request.args.get('type_id')
    dict_type = get_dict_type()
    if type_id!=None or request.method=='POST':
        dict_item=get_dict_item(type_id)
        return render_template('system-dict.html',form=form,dict_type=dict_type,dict_item=dict_item,type_id=type_id)
    else:
        return render_template('system-dict.html',form=form,dict_type=dict_type,type_id=type_id)

@login.route('/system_dict_add', methods=['GET', 'POST'])
@login_required
def system_dict_add():
    form = DictTypeFrom()
    system_dict_data = DictType(type_id=None,key=form.key.data,value=form.value.data,desc=form.desc.data,status=form.status.data)
    if request.method=='POST':
        if dict_add(data=system_dict_data):
            flash("添加成功")
        else:
            flash("sql执行异常")
        return redirect(url_for('login.system_dict'))
    return render_template('system-dict-add.html',form=form)

@login.route('/system_dict_update', methods=['GET', 'POST'])
@login_required
def system_dict_update():
    type_id = request.args.get('type_id')
    dict_type = get_dict_type_by_typeid(type_id)
    #表单修改时展示原数据 obj=dict_type
    form = DictTypeFrom(obj=dict_type)
    if request.method=='POST':
        print(type_id)
        system_dict_data={"type_id":type_id,"key":form.key.data,"value":form.value.data,"desc":form.desc.data,"status":form.status.data}
        print(system_dict_data)
        if dict_type_update(type_id,system_dict_data):
            flash("修改成功")
        else:
            flash("sql执行异常")
        return redirect(url_for('login.system_dict'))
    return render_template('system-dict-update.html', form=form,type_id=type_id)

@login.route('/system_dict_delete', methods=['GET', 'POST'])
@login_required
def system_dict_delete():
    type_id = request.args.get('type_id')
    #todo:模型查找字段不能 取指定值 不能使用len()方法
    # print(type(get_dict_type_by_typeid(type_id)[0]))
    # print(get_dict_item(get_dict_type_by_typeid(type_id)[0]))
    if get_dict_item(get_dict_type_by_typeid(type_id)[0])==None:
        if dict_type_delete(type_id):
            flash("修删除成功")
        else:
            flash("sql执行异常")
    return redirect(url_for('login.system_dict'))

@login.route('/system_dict_item_add', methods=['GET', 'POST'])
@login_required
def system_dict_item_add():
    form = DictItemFrom()
    type_id = request.args.get('type_id')
    print(type_id)
    system_dict_data = DictItem(id=None,type_id=type_id,sort_id=form.sort_id.data,key=form.key.data,value=form.value.data,desc=form.desc.data,status=form.status.data)
    print(system_dict_data)
    if request.method=='POST':
        if dict_add(data=system_dict_data):
            print(1)
            flash("添加成功")
        else:
            print(2)
            flash("sql执行异常")
        return redirect(url_for('login.system_dict',type_id=type_id))
    return render_template('system-dict-item-add.html',form=form,type_id=type_id)

#登出
@login.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
    # 将session中的用户信息删除;
    flash("你已退出，请重新登录")
    session.pop('username', None)
    return redirect(url_for('login.login'))

#用户注册路由
@login.route('/register', methods=['GET', 'POST'])
def register():
    # 如果请求为post
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        print(username, password,repassword)
        from app import db
        if password == repassword:
            user = User(username, password)
            user.set_password(password) #密码加密
            #{'username': 'admin', 'password': '123456'}
            db.session.add(user)
            db.session.commit()
            return '注册成功'
        else:
            return '两次密码不一致'
    # 请求为get
    return render_template('register.html')

#用户登录路由
@login.route('/', methods=['GET', 'POST'])
@login.route('/login', methods=['GET', 'POST'])
def login():
    # if request.method == 'POST':
    #     username = request.form['username']
    #     password = request.form['password']
    #     print(username,password)
    #
    #     if not username or not password:
    #         flash('Invalid input.')
    #         return redirect(url_for('login'))
    #     user = User.query.filter_by(username=username).first()
    #     print(user.username,user.password)
    #     if not user:
    #         flash("用户不存在")
    #         return redirect(url_for('login.login'))
    #     if username == user.username and user.check_password(password):
    #         login_user(user)  # 登入用户
    #         flash('Login success.')
    #         print("登录成功")
    #         return redirect(url_for('login.index'))  # 重定向到主页
    #     flash('Invalid username or password.')  # 如果验证失败，显示错误消息
    #     return redirect(url_for('login_old.html'))  # 重定向回登录页面
    # return render_template('login_old.html')
    form = LoginForm()
    if form.validate_on_submit():
        '''
        #如果用户提交表单，并且数据通过验证
        if request.method == 'POST' and form.validate(): 方法简写 form.validate_on_submit()
        '''
        username = form.username.data
        password = form.password.data
        print(username,password)
        if not username or not password:  #如何用户名密码为空 重定向到login
            '''
            flash和它的名字一样，是闪现，意思就是我们的消息只会显示一次，当我们再次刷新也面的时候，它就不存在了，
            而正是这点，它经常被用来显示一些提示消息，比如登陆之后，显示欢迎信息等
            '''
            flash('Invalid input.')
            return redirect(url_for('login'))
        user = User.query.filter_by(username=username).first() #查询数据库
        if not user:
            flash("No username")
            return redirect(url_for('login.login'))
        if username == user.username and user.check_password(password):
            login_user(user)  # 登入用户 login_user可以记录/保存当前成功登陆的用户
            print("登录成功")
            ## 存储用户登录信息; session可以认为时字典对象
            session['username']= username
            return redirect(url_for('login.index'))  # 重定向到主页
        flash('Invalid username or password.')  # 如果验证失败，显示错误消息
        return redirect(url_for('login.login'))  # 重定向回登录页面
    return render_template('login.html',form=form)